//
//  ConfigHelper.m
//  DiscountClub
//
//  Created by Philip Chew on 3/3/12.
//  Copyright (c) 2012 articwind@gmail.com. All rights reserved.
//

#import "ConfigHelper.h"

static ConfigHelper *_instance=nil;
@implementation ConfigHelper
@synthesize appSettings, appSettingsPath;

//Loads up configuration objects and copies them to the documents folder if they do not exist
- (void) loadConfigObjects {
    if(appSettings == nil) {
		NSError *error;
		NSString *appSettingsName = @"appSettings.plist";
		
		NSArray *allPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *docDir = [allPaths objectAtIndex:0];
		self.appSettingsPath = [docDir stringByAppendingPathComponent:appSettingsName];
		
		NSFileManager *fileManager = [NSFileManager defaultManager];
		if(! [fileManager fileExistsAtPath:appSettingsPath]) {
			NSString *orgPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:appSettingsName];
			[fileManager copyItemAtPath:orgPath toPath:appSettingsPath error:&error];
		}
		
        appSettings = [[NSMutableDictionary alloc] initWithContentsOfFile:appSettingsPath];
    }
}

//Gets an app settings value from the appSettings plist
- (NSString *) getAppSettingsValue:(NSString *)keyName 
{
	if(appSettings != nil )
    {
        if( [appSettings objectForKey:keyName] != nil) 
        {
			NSString *result = [appSettings objectForKey:keyName];
            return result;
        }
        
        else
            return @"";
    }
    else {
        return @"";
    }
}

//Sets a settings value into the appSettings file
- (void) setAppSettingsValue:(NSString *)value forKey:(NSString *)keyName 
{
	if(appSettings != nil) {
		[appSettings setValue:value forKey:keyName];
		[appSettings writeToFile:self.appSettingsPath atomically:YES];		
	}
}

//Returns a singleton instance of ConfigHelper
+ (ConfigHelper *) sharedInstance 
{
	if(_instance == nil) {
		_instance = [[ConfigHelper alloc] init];
		[_instance loadConfigObjects]; //To instantiate any local members if needed;
	}   
    return _instance;
}

//Allocates self within a zone, and only returning itself once (as a singleton)
+ (id)allocWithZone:(NSZone *)zone 
{
	if(_instance == nil) {
		_instance = [super allocWithZone:zone];
		return _instance;
	}
    
    return nil;
}

//Copy with zone
- (id) copyWithZone:(NSZone *) zone 
{
    return self;
}

//Permanently retains itself
- (id) retain 
{
    return self;
}

//Doesn't get to be released, so has max retain count
- (unsigned) retainCount 
{
    return UINT_MAX;
}

//Ensure release does nothing
- (oneway void)release
{
	//do nothing
}

//Auto release
- (id) autorelease 
{
    return self;
}

@end

